#include "widget.h"
#include "ui_widget.h"
#include<QPaintEvent>
#include<QPainter>
#include<QPixmap>
#include<QCursor>
#include<QMetaEnum>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget),
      timer(new QTimer(this)),
      menu(new QMenu(this))
{
    ui->setupUi(this);
    this->setWindowFlag(Qt::FramelessWindowHint);
    this->setAttribute(Qt::WA_TranslucentBackground);

    this->installEventFilter(new DragFilter);

    connect(timer,&QTimer::timeout,[this](){
        static int index=0;
        auto paths=this->action_map.value(this->cur_role_act);
        this->cur_role_pix=paths[index++ % paths.size()];
        this->update();
  });

    initMenu();

    loadRoleActRes();

    showActAnimation(RoleAct::Swing);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::showActAnimation(RoleAct k)
{
    timer->stop();
    this->cur_role_act=k;
    timer->start(200);
}

void Widget::onMenuTriggered(QAction *action)
{
    QMetaEnum me=QMetaEnum::fromType<RoleAct>();
    bool ok;
    int k=me.keyToValue(action->text().toStdString().c_str(),&ok);
    if(!ok)
        return;
    showActAnimation(static_cast<RoleAct>(k));
}



void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    QPixmap pix;
    pix.load(this->cur_role_pix.toLocalFile());

    painter.drawPixmap(0,0,pix);
}

void Widget::contextMenuEvent(QContextMenuEvent *event)
{
    this->menu->popup(QCursor::pos());
}

void Widget::loadRoleActRes()
{
    auto addRes=[this](RoleAct k,QString path,int count)
    {
        QList<QUrl>paths;
        char buf[260];
        for (int i=0;i<count;i++) {
            memset(buf,0,sizeof(buf));
            sprintf_s(buf,path.toStdString().c_str(),i);
            paths.append(QUrl::fromLocalFile(buf));
        }
        action_map.insert(k,paths);
    };
    addRes(RoleAct::SayHello,":/sayhello/img/sayhello/%d.jpg",9);
    addRes(RoleAct::Swing,":/swing/img/swing/%d.jpg",7);

}

void Widget::initMenu()
{
    menu->addAction("SayHello");
    menu->addAction("Swing");

    QAction * act=new QAction("Hide");
    connect(act,&QAction::triggered,[this](){
        this->setVisible(false);
    });
    menu->addAction(act);
    connect(this->menu,&QMenu::triggered,this,&Widget::onMenuTriggered);
}

